/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int longestUnivaluePath(TreeNode* root) {
        if(root==nullptr){return 0;}
        int ans=0;
        postorder(root,ans);
        return ans;
    }
    int postorder(TreeNode* root,int& ans){
        if(root==nullptr){return 0;}
        int left=postorder(root->left,ans);
        int right=postorder(root->right,ans);
        left=(root->left!=nullptr && root->val==root->left->val)?left+1:0;
        right=(root->right!=nullptr&& root->val==root->right->val)?right+1:0;
        ans=max(ans,left+right);
        return max(left,right);
    }
};